<template>
  <div class="Main">
    <div class="MainTitle">店铺Banner</div>
    <div class="MianContent">
      <div>
        <a-button
        type="primary"
        style="margin:0 20px 20px 0"
        size="large"
        @click="addBanner"
        :disabled="listData.length < 3?false:true"
        >新增Banner</a-button>
        注：最多三条banner
      </div>
      <a-table
        :columns="listfields"
        :data-source="listData"
        :bordered="true"
        :pagination="false"
      >
        <div slot="action" slot-scope="row, index">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-around;
              margin-bottom: 6px;
            "
          >
            <a-button type="primary" size="small" @click="toEdit(index)"
              >编辑</a-button
            >
            <a-popconfirm
              placement="bottom"
              ok-text="删除"
              cancel-text="取消"
              @confirm="DeleteItem(index)"
            >
              <template slot="title">
                <p>警告</p>
                <p>此操作将永久删除该banner, 是否继续?</p>
              </template>
              <a-button type="danger" size="small">删除</a-button>
            </a-popconfirm>
          </div>
        </div>
        <div slot="url_type" slot-scope="row, index">
            {{row==1?'tabbar页面':row==2?'二级页面':''}}
        </div>
        <div slot="logo" slot-scope="row, index">
          <img
            style="width: 50px; height: 50px"
            @click="seeImg(index)"
            :src="row"
            alt=""
          />
        </div>
      </a-table>
      <Pagination
        :total="total"
        v-model="pageno"
        :pageSize.sync="pagesize"
        @change="handlePageChange"
        @onShowSizeChange="onShowSizeChange"
      ></Pagination>
      <a-modal
        title="banner详情"
        v-model="modalShow"
        centered
        ok-text="确认"
        :maskClosable="false" 
        cancel-text="取消"
        @cancel="cancelBtn"
        @ok="modalSubmit"
        :width="700"
      >
        <div style="padding-left: 10px">
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-model-item label="跳转类型" prop="url_type">
              <a-radio-group name="radioGroup" v-model="form.url_type">
                <a-radio :value="1"> tabbar页面 </a-radio>
                <a-radio :value="2"> 二级页面 </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="跳转链接" prop="url">
              <a-input
                v-model="form.url"
                placeholder="请输入跳转链接"
                allowClear
              />
            </a-form-model-item>
            <a-form-model-item label="banner图" prop="logo">
              <UploadImage v-if="modalShow" v-model="form.logo" :maxNum="1"></UploadImage>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-modal>
      <a-modal v-model="LookImages" :footer="null" centered>
        <div style="margin: 10px">
          <img :src="SelectImg" style="width: 100%; height: 100%" />
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import { ACCESS_TOKEN, USER_DATA } from '@/store/mutation-types';
import { mapGetters, mapState, mapActions } from "vuex";
import { showErrors, showError, showSuccess } from "@/utils/showMsg";
import Pagination from "@/components/common/pagination.vue";
import UploadImage from "@/components/common/Upload";
import {
  BannerDetail,
  BannerEdit,
} from "@/api/api.js";
export default {
  name: "list",
  components: {
    Pagination,
    UploadImage,
  },
  data() {
    return {
      modalShow: false,
      pageno: 1, //默认第几页
      pagesize: 10, //一页显示多少条数据
      total: 0, //总数
      listData: [], //表格数据
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      keyword: "",
      listfields:[
        {title: '图片', dataIndex: 'logo', scopedSlots: { customRender: 'logo' },align: 'center',},
        {title: '跳转链接', dataIndex: 'url',align: 'center',},
        {title: '跳转类型', dataIndex: 'url_type', scopedSlots: { customRender: 'url_type' },align: 'center',},
        {title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' },align: 'center',width:200},
      ],
      form: {
        url: "",
        logo: [],
        url_type: ''
      },
      rules: {
        logo: [{ type:'array',required: true, message: '请上传banner图', trigger: 'change', }, ],
      },
      LookImages: false,
      SelectImg: "",
      current:'1',

      addType:'', //操作类型，add-新增，edit-编辑
      editKey:'', //要编辑项的key
    };
  },
  computed: {
    // ...mapState({
    //   listfields: (state) => state.ProductBrand.fields, //获取table头
    // }),
  },
  mounted() {
    // this.GetFields();
    this.GetList();
  },
  methods: {
    // ...mapActions({
    //   GetFields: "ProductBrand/GetFields", //获取table头
    // }),

    // 查看图片
    seeImg(row) {
      const that = this;
      that.LookImages = true;
      that.SelectImg = row.logo;
    },

    // 选择tabs
    selectTabs(){
      const that = this;
      that.pageno = 1;
      that.pagesize = 10;
      that.GetList()
    },

    // 获取品牌列表
    async GetList() {
      const that = this;
      const user = Vue.ls.get(USER_DATA);
      let params = {
        store_id:user.identityId,
      };
      let res = await BannerDetail(params);
      if (res.data.code == 1) {
        let data = res.data.data;
        let List = [];
        if(data.banner_img){
            let bannerData = JSON.parse(data.banner_img);
            if(Array.isArray(bannerData)){
                List = bannerData;
            }else if(typeof bannerData == 'object' && bannerData != null){
                List.push(bannerData);
            }

            List.forEach((item,index)=>{
                item.key = index+1
            })
        }

        that.listData = List;
        that.total = List.length;
        // console.log(this.listData,'--')
      } else {
        showError(res.data.msg);
      }
    },
    addBanner(){
        const that = this;
        that.addType = 'add';
        that.modalShow = true;
    },
    // 弹出确定
    async modalSubmit() {
      let that = this;
      const user = Vue.ls.get(USER_DATA);
      that.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!that.form.logo.length) {
            showError("请上传banner图");
            return;
          }
          let arrData = [];
          if(that.addType == 'add'){ //新增
            let obj={}
            obj = {
                url_type: that.form.url_type,
                url: that.form.url,
                logo: that.form.logo[0].url
                ? that.form.logo[0].url
                : that.form.logo[0],
            }
            that.listData.push(obj);
          }else if(that.addType == 'edit'){
            arrData = JSON.parse(JSON.stringify(that.listData)); //把数据重新赋值一个数组
            let dataIndex = arrData.findIndex(item=>item.key == that.editKey);
            if(dataIndex != -1){
                arrData[dataIndex].url_type = that.form.url_type;
                arrData[dataIndex].url = that.form.url;
                arrData[dataIndex].logo = that.form.logo[0].url
                ? that.form.logo[0].url
                : that.form.logo[0];
            }
          }
          let bannerDataArr = that.addType == 'add'?JSON.stringify(that.listData):JSON.stringify(arrData);
          let params = {
            store_id:user.identityId,
            banner_img:bannerDataArr
          };
            //编辑/新增banner
            let res = await BannerEdit(params);
            if (res.data.code == 1) {
              showSuccess(`${that.addType == 'add'?'新增':'编辑'}成功`);
              that.modalShow = false;
              that.cancelBtn();
              that.GetList();
            } else {
              showError(res.data.msg);
            }
        }
      });
    },
    // 弹出取消
    cancelBtn() {
      const that = this;
      that.$refs.ruleForm.resetFields();
      that.form.url_type = '';
      that.form.url = '';
      that.form.logo = [];
      that.form.addType = '';
      that.form.editKey = '';
      // that.$refs.uploadImg.clearFile()
      that.modalShow = false;
    },

    // 删除品牌
    async DeleteItem(row) {
      const that = this;
      const user = Vue.ls.get(USER_DATA);
      let arrData = JSON.parse(JSON.stringify(that.listData));
      let dataIndex = arrData.findIndex(item=>item.key == row.key);
    //   console.log(dataIndex,'dataIndex')
      if(dataIndex != -1){
        arrData.splice(dataIndex,1)
        // console.log(arrData,'arrData')
      }
      let params = {
        store_id:user.identityId,
        banner_img:JSON.stringify(arrData)
      };
      let res = await BannerEdit(params);
      if (res.data.code == 1) {
        showSuccess(`删除成功`);
        that.GetList();
      } else {
        showError(res.data.msg);
      }
    },

    // 编辑品牌
    toEdit(row) {
      console.log(row);
      const that = this;
      that.addType = 'edit';
      that.editKey = row.key;
      that.form.url = row.url;
      that.form.url_type = row.url_type;
      that.form.logo = row.logo ? [{ url: row.logo }] : [];
      that.modalShow = true;
    },

    //分页器
    handlePageChange(pageno, pagesize) {
      //点击第几页触发的函数
      this.pageno = pageno;
      this.pagesize = pagesize;
      this.GetList(); //这个是向后台请求的数据函数
    },
    //切换每页显示多少条
    onShowSizeChange(current, size) {
      //改变每页显示条目数的函数
      //pagesize 变化的回调
      this.pageno = current;
      this.pagesize = size;
      this.GetList(); //这个是向后台请求的数据函数
    },
  },
};
</script>

<style scoped lang="stylus">
.editable-row-operations a {
  margin-right: 12px;
}
.Main {
  border-radius: 10px;
  overflow: hidden;
  background: #fff;
  .MainTitle {
    font-size: 24px;
    color: #333;
    margin: 10px 20px;
    position: relative;
  }
  .MainTitle:before {
    content: '';
    width: 40px;
    height: 12px;
    background: linear-gradient(270deg, rgba(0, 158, 238, 0) 0%, rgba(0, 158, 238, 0.3) 100%);
    position: absolute;
    bottom: 2px;
    left: 0;
  }
  .MianContent {
    padding: 10px 20px 20px 20px;
    .MainTopAction {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .MainTopActionView {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .MainTopActionOne {
          margin-right: 30px;
          span {
            margin-right: 20px;
          }
        }
        .MainTopActionTwo {
          span {
            margin-right: 20px;
          }
        }
      }
      .MainTopActionThree {
        display: flex;
        align-items: center;
        margin-left: 20px;
      }
    }
  }
}
</style>